<template>
    <div>
        <el-button type="primary" @click="handleEdit">新增</el-button>
        <!-- <el-input v-for="(condition, index) in query.SearchConditions" v-model="condition.Value" :key="index"
            style="width: 240px" clearable :placeholder="'Please input ' + condition.FieldName" />
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button type="primary" @click="clearQuery">重置</el-button> -->
    </div>
    <el-table height="800px" :show-overflow-tooltip="true" :data="tableData">
        <!-- <el-table-column v-for="item in bgcolumnNames" :prop="item.Name" :label="item.label" /> -->
        <el-table-column v-for="item in bgcolumnNames" :key="item.Name" :prop="item.Name" :label="item.Label">
            <template #default="{ row }">
                <!-- {{ row }} -->
                <span v-if="item.ControlType === 7">{{ item.EnumDic[row[item.Name]] }}</span>
                <span v-else>{{ row[item.Name] }}</span>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
                <el-button link type="primary" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row)">
                    <template #reference>
                        <el-button link type="danger" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible" title="编辑">
        <el-form @submit.native.prevent v-for=" item in bgcolumnNames" :model="editItem">
            <el-form-item v-if="item.IsEditable" :label="item.Label" :label-width="formLabelWidth">
                <JSCodeMirror v-if="item.ControlType == 1" v-model:value="editItem[item.Name]"></JSCodeMirror>

                <!-- <div v-else-if="item.ControlType == 7">
                    <span v-for="(label, value) in item.EnumDic"> {{ label }},{{ value }} \\\</span>
                </div> -->
                <el-select v-else-if="item.ControlType == 7" v-model="editItem[item.Name]" placeholder="请选择">
                    <el-option v-for="(label, value) in item.EnumDic" :label="label" :value="Number(value)" />
                </el-select>
                <el-input v-else v-model="editItem[item.Name]" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="onTestConnect">测试连接</el-button>

                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="onConfirm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, nextTick, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import JSCodeMirror from '../components/JSCodeMirror.vue'; // 引入 CodeEditor 组件


import api from '../api'
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

var columns = reactive({})
const query = reactive({
    pageIndex: 1,
    pageSize: 30,
    SearchConditions: [{
        FieldName: 'Name',
        ConditionType: 1,
        Value: ''
    }, {
        FieldName: 'Content',
        ConditionType: 1,
        Value: ''
    }]
})

// var label=['']
var tableData = ref([])
var editItem = reactive({});

const onTestConnect = () => {

    api.post('DBConfig/TestConnect', editItem).then(res => {

        if (res.Code == 200) {
            ElMessage.success('连接成功')
        }

    })
}
const clearQuery = async () => {
    query.pageIndex = 1 // 重置页码
    query.pageSize = 30 // 重置每页条数
    query.SearchConditions.forEach(condition => {
        condition.Value = ''
    })
}
// 定义方法
const getDataList = async () => {
    // var postData = {
    //     pageIndex: 1,
    //     pageSize: 30,
    // }

    var res = await api.post('DBConfig/List', query)

    var data = res.Data
    tableData.value = data.list
    bgcolumnNames = data.columnNames
};
// const getSearchItem = async (name) => {
//     

//     return query.SearchConditions.find(x => x.FieldName == name)
// }

/**
 * 计算属性 - 获取表格显示的列名
 * 该函数会根据当前表格数据动态计算出应显示的列名，排除特定的字段（如id、创建时间等）。
 * 
 * @returns {Array} 返回一个数组，包含需要在表格中显示的列名。
//  */
// const columnNames = computed(() => {
//     // 当表格数据为空时，直接返回空数组
//     if (!tableData.value[0]) {
//         return []
//     }
//     const keys = Object.keys(tableData.value[0]);

//     // 定义需要移除的字段名列表
//     const itemsToRemove = ["id", "createTime", "updateTime", "isDeleted"];
//     // 筛选出不需要移除的字段名
//     let newKeys = keys.filter(item => !itemsToRemove.includes(item))

//     return newKeys
// })
var bgcolumnNames = []
const getUIType = (colName) => {
    colName = colName.toLowerCase()
    var findItem = bgcolumnNames.find(x => x.name.toLowerCase() == colName)
    return findItem.ControlType
}

/**
 * 确认并更新模板信息
 * 无参数
 * 无明确返回值，但会通过控制台输出和界面提示更新结果
 */
const onConfirm = async () => {
    // 提交编辑中的模板信息至服务器

    var res = await api.post('DBConfig/Update', editItem)

    // 根据服务器返回代码判断操作成功与否
    if (res.Code == 200) {
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: res.Message,
            type: 'success',
        })
        getDataList()
        // 关闭当前对话框
        dialogFormVisible.value = false
    }
}
const handleDelete = async item => {

    item.isDeleted = true
    var res = await api.post('DBConfig/Update', item)
    if (res.Code == 200) {
        // 成功更新，显示成功消息并刷新列表
        ElMessage({
            message: "删除成功",
            type: 'success',
        })
        getDataList()
    }
}

const handleEdit = async (item) => {

    editItem = reactive(JSON.parse(JSON.stringify(item)));
    dialogFormVisible.value = true
}

onMounted(async () => {
    try {

        getDataList()

        // const data = await $api.get('/your-api-endpoint');
        // 使用获取的数据
    } catch (error) {

    }
});


</script>

<style>
.el-input {
    margin: 0 5px;
}

.CodeMirror {
    margin-right: 100px;
}

.CodeMirror-sizer {
    min-width: 500px !important;
}

.el-dialog__body {
    overflow: auto;
    max-height: 500px;
}
</style>